﻿package at.geoathome.utils.loader
{

	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.HTTPStatusEvent;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	
	/**
	* ...
	* @author Georg Kamptner
	* todo: - test it
	* 		- caching
	*/
	public class XMLLoader extends EventDispatcher
	{
		
		private var _req:URLRequest;
		private var _loading:Boolean;
		private var _xml:XML;
		private var _loader:URLLoader;

		public function XMLLoader(url:String = null)
		{
			_req = new URLRequest(url);
			_xml = new XML();
			
			_loader = new URLLoader();
			_loader.addEventListener(Event.COMPLETE, xmlLoaded);
			_loader.addEventListener(Event.OPEN, onLoadStarts);
			_loader.addEventListener(HTTPStatusEvent.HTTP_STATUS, delegate);
			_loader.addEventListener(ProgressEvent.PROGRESS, delegate);
			_loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, delegate);
			_loader.addEventListener(IOErrorEvent.IO_ERROR, delegate);
		}

	   
		/**
		 * loads an xml file from the specified url. if you specified it already in the constructor you can omit it.
		 */
		public function load( request:URLRequest = null ):void
		{
			if(request != null)
				_req = request;
				
			_loader.load(_req);
		}

	   
		/**
		 * stops the download of the file
		 */
		public function stop(  ):void
		{
			if( _loading ) _loader.close();
				onLoadEnds();
		}

	   
		/**
		 * returns the xml
		 */
		public function getResult():XML
		{
			return _xml;
		}

	   
		/**
		 * catch the event when the xml is loaded and assign it.
		 */
		private function xmlLoaded( event:Event ):void
		{
			_xml = XML(_loader.data);
			onLoadEnds(event);
		}

	   
		/**
		 * simply delegates the event
		*/
		private function delegate( event:Event ):void
		{
			dispatchEvent(event);
		}
		
		/**
		 * should be called when the load starts
		 */
		private function onLoadStarts( e:Event = null ):void
		{
			_loading = true;
			if( e != null ) dispatchEvent(e);
		}

	   
		/**
		 * should be called when the load is finished
		 */
		private function onLoadEnds( e:Event = null ):void
		{
			_loading = false;
			if( e != null ) dispatchEvent(e);
		}
	}
	
}

